package algorithm.queue;


/**
 * @author bingo
 * @Description    基于链表实现队列 链表头出队，链表尾入队
 * @Date 2018/6/4
 */
public class LinkedListQueue<E> implements Queue<E> {

    private class Node<E>{

        public E data;

        public Node next;

        public Node() {
            this(null,null);
        }

        public Node(E data) {
            this(data,null);
        }

        public Node(E data, Node next) {
            this.data = data;
            this.next = next;
        }

    }

    private Node<E> head;

    private Node tail;

    private int size;

    public LinkedListQueue() {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    @Override
    public void enqueue(E e) {
        if(tail==null){
            Node node = new Node(e);
            tail = node;
            head = node;
        }
        else{
            Node node = new Node(e);
            tail.next = node;
            tail = node;
            }

         size++;
    }

    @Override
    public E dequeue() {
        Node<E> delNode = head;
        head = head.next;
        if(head==null){
            tail=null;
        }
        size--;
        return  delNode.data;
    }

    @Override
    public E front() {
        return head.data;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public String toString(){

        StringBuilder stringBuilder = new StringBuilder();
        Node node = head;
        stringBuilder.append("LinkedListQueue[");
        while (node!=null){
            stringBuilder.append(node.data+"->");
            node = node.next;
        }
        stringBuilder.append("null");
        return  stringBuilder.toString();
    }

    public static void main(String[] args) {
        LinkedListQueue linkedListQueue = new LinkedListQueue();
        for(int i=0;i<10;i++){
            linkedListQueue.enqueue(i);
            System.out.println(linkedListQueue);
        }
        for(int i=0;i<10;i++){
            linkedListQueue.dequeue();
            System.out.println(linkedListQueue);
        }

    }

}
